package com.wkq.net.work

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import com.wkq.net.util.DownSecretUtil
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/6/30 10:40
 *
 *@Desc: 资源下载的Work
 */
class ResourceDownloadWorker(var context: Context, params: WorkerParameters) : CoroutineWorker(context, params ){
    override suspend fun doWork(): Result {
        val url = inputData.getString("url")
        var fileName= inputData.getString("fileName")
        if (url.isNullOrEmpty()||!url.startsWith("http"))return Result.failure()
        val dirFilePath = inputData.getString("rootPath")
        if (dirFilePath.isNullOrEmpty())return Result.failure()

        return try {
            val saveFileName = if (!fileName.isNullOrEmpty()){
                fileName
            }else{
                DownSecretUtil.getMD5Result(url)
            }
            val dir = File(dirFilePath)
            if (!dir.exists()) dir.mkdirs()
            val outFile = File(dir, saveFileName)
            if (outFile.exists()) return  Result.success(bulidData(inputData.getString("id")?:"",outFile.absolutePath))

            val request = Request.Builder().url(url).build()
            val response = OkHttpClient().newCall(request).execute()

            if (response.isSuccessful) {
                val body = response.body ?: return Result.failure()
                body.byteStream().use { input ->
                    outFile.outputStream().use { output ->
                        input.copyTo(output)
                    }
                }
                Result.success(bulidData(inputData.getString("id")?:"",outFile.absolutePath))
            }else if (response.code==404){
                Result.failure()
            } else {
                Result.retry()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Result.retry()
        }

    }
    private fun bulidData(id: String, filePath: String): Data {
        return Data.Builder()
            .putString("id",id)
            .putString("path", filePath)
            .build()
    }


}